﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GMS.MainClasses;
using GMS.ServiceFunctions.FunctionForControls;
using GMS.ServiceFunctions.Data;
using GMS.MainForm;
using GMS.Dinasty.Specifications;
using GMS.Dinasty.DAL;
using GMS.BasicControls;
using System.Data.SqlClient;


namespace GMS.Dinasty.ReferenceGoods
{
    public partial class ReferenceGoods : ChildForms
    {
        private DataGridView DGWR;
        public ReferenceGoods()
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;

            StoredProcedures = new String[6];

            StoredProcedures[0] = "select * from Goods";
            StoredProcedures[1] = "MakeRootNode";
            StoredProcedures[2] = "DSelectGoodsPropertiesByIdGood";
            StoredProcedures[3] = "DSelectPropertiesByGroup";
            StoredProcedures[4] = "DUpdateValueOptions";
            StoredProcedures[5] = "DInsertGoodPropertie";
            ConnectionString = "server=pavel;uid=pavel;pwd=123456;database=GMSDatabase";

            createTablePropertie();
            dataGridView1.DataSource = tableProperties;
        }

        public ReferenceGoods(DataGridView DGWR)
        {
            InitializeComponent();
            dataGridView1.AutoGenerateColumns = false;
            this.DGWR = DGWR;

            StoredProcedures = new String[6];

            StoredProcedures[0] = "select * from Goods";
            StoredProcedures[1] = "MakeRootNode";
            StoredProcedures[2] = "DSelectGoodsPropertiesByIdGood";
            StoredProcedures[3] = "DSelectPropertiesByGroup";
            StoredProcedures[4] = "DUpdateValueOptions";
            StoredProcedures[5] = "DInsertGoodPropertie";

            createTablePropertie();
            dataGridView1.DataSource = tableProperties;
        }

        FunctionForTreeView FFTV = new FunctionForTreeView();
        BindingSource bsMenu = new BindingSource();
        TreeNode SelectedNode = new TreeNode();

        ReturnData rd = new ReturnData();
        DataAccessGoods DAG = new DataAccessGoods();
        private void RefreshTreeView()
        {
            bsMenu.DataSource = rd.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);
            //bsMenu.DataSource = MRF.ReturnDataSetDB(ConnectionString, StoredProcedures[0]);

            bsMenu.DataMember = "table";
            FFTV.FillTreeView(treeView1, bsMenu, "IdGoods", "IdId", "Caption");
            SelectedNode.Expand();
        }

        private void ReferenceGoods_Activated(object sender, EventArgs e)
        {
            RefreshTreeView();
        }

        private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            groupBox2.Text = "Карточка - " + e.Node.Text;
        }

        private void acceptButton1_Click(object sender, EventArgs e)
        {
            try
            {
                string _value = treeView1.SelectedNode.Tag.ToString() + ";" + treeView1.SelectedNode.Text + ";" + tableProperties.Select(string.Format("IdProperties = 7"))[0]["PropertieValue"].ToString();
                string _idValue = treeView1.SelectedNode.Tag.ToString();
                string _units = tableProperties.Select(string.Format("IdProperties = 1"))[0]["PropertieValue"].ToString();
                string _price = tableProperties.Select(string.Format("IdProperties = 5"))[0]["PropertieValue"].ToString();
                string _quantity = "0";
                string _lowprice = "0";

                DGWR.Rows[DGWR.CurrentCell.RowIndex].Cells[DGWR.CurrentCell.ColumnIndex].Value = _value;
                DGWR.CurrentRow.Cells["idcaption"].Value = _idValue;
                DGWR.Rows[DGWR.CurrentCell.RowIndex].Cells[DGWR.CurrentCell.ColumnIndex + 1].Value = _units;
                DGWR.Rows[DGWR.CurrentCell.RowIndex].Cells[DGWR.CurrentCell.ColumnIndex + 2].Value = _quantity;
                DGWR.Rows[DGWR.CurrentCell.RowIndex].Cells[DGWR.CurrentCell.ColumnIndex + 3].Value = _price.Replace('.', ',');
                DGWR.Rows[DGWR.CurrentCell.RowIndex].Cells[DGWR.CurrentCell.ColumnIndex + 4].Value = _lowprice;

            }
            catch (Exception exception)
            {

                MessageBox.Show(exception.ToString(), "Ошибка!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            
        }
        DataTable tableProperties = new DataTable();
        SqlDataAdapter adapter = new SqlDataAdapter();
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            //SelectGoodOptions(int.Parse(treeView1.SelectedNode.Tag.ToString()), StoredProcedures[2]);
            tableProperties.Clear();
            idGood = int.Parse(treeView1.SelectedNode.Tag.ToString());
            CreateOptionsDataAdapter(idGood);
        }
        private void SelectGoodOptions(int IdGood, string StoredProcedures)
        {
            tableProperties = DAG.PropertiesTable(StoredProcedures, ConnectionString, IdGood);
            dataGridView1.DataSource = tableProperties;
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Columns[e.ColumnIndex].Name == "value")
            {
                string val = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[dataGridView1.CurrentCell.ColumnIndex - 1].Value.ToString();
                int idProp = int.Parse(tableProperties.Rows[dataGridView1.CurrentRow.Index]["IdProperties"].ToString());
                if (idProp == 1)
                {
                    UnitsList ul = new UnitsList();
                    ul.applyLinkLabel.LinkClicked += new LinkLabelLinkClickedEventHandler(applyLinkLabel_LinkClicked);
                    ul.ConnectionString = ConnectionString;
                    Point pt = this.dataGridView1.PointToClient(Control.MousePosition);
                    ul.Location = pt;
                    this.Controls.Add(ul);
                    ul.BringToFront();
                }
            }
        }

        void applyLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            dataGridView1.CurrentCell.Value = ((sender as LinkLabel).Parent as UnitsList).dataGridView1.SelectedRows[0].Cells["Caption"].Value.ToString();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F1)
            {
                GroupList gl = new GroupList();
                gl.ConnectionString = ConnectionString;
                Point location = new Point(textBox1.Left, textBox1.Bottom);
                gl.Location = location;
                this.Controls.Add(gl);
                gl.BringToFront();
                gl.applylinkLabel.Click += new EventHandler(applylinkLabel_Click);
            }
        }
        SqlDataAdapter emptyPropertieAdapter = new SqlDataAdapter();
        DataTable template = new DataTable();
        void FillPropertieSet(int ID)
        {
            emptyPropertieAdapter.SelectCommand = new SqlCommand(StoredProcedures[3], new SqlConnection(ConnectionString));
            emptyPropertieAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
            emptyPropertieAdapter.SelectCommand.Parameters.Add("@IdGoods", SqlDbType.Int).Value = ID;

            emptyPropertieAdapter.Fill(template);
            tableProperties.Clear();
            foreach (DataRow dr in template.Rows)
            {
                DataRow row = tableProperties.NewRow();
                row["IdProperties"] = dr["IdProperties"];
                row["CaptionProperties"] = dr["CaptionProperties"];
                row["PropertieValue"] = dr["PropertieValue"];
                tableProperties.Rows.Add(row);
                
            }
            DataRow row1 = tableProperties.NewRow();
            tableProperties.Rows.Add(row1);
            //tableProperties.AcceptChanges();
        }
        int idGroup;
        void applylinkLabel_Click(object sender, EventArgs e)
        {
            idGroup = int.Parse(((sender as LinkLabel).Parent as GroupList).dataGridView1.SelectedRows[0].Cells["idgroup"].Value.ToString());
            tableProperties.Clear();
            FillPropertieSet(idGroup);
        }
        int idGood;
        private void CreateOptionsDataAdapter(int ID)
        {
            adapter.SelectCommand = new SqlCommand(StoredProcedures[2], new SqlConnection(ConnectionString));
            adapter.SelectCommand.CommandType = CommandType.StoredProcedure;

            SqlParameter selectParameter = null;
            selectParameter = adapter.SelectCommand.Parameters.Add("@IdGoods", SqlDbType.Int);
            selectParameter.Value = ID;
            adapter.Fill(tableProperties);

            adapter.InsertCommand = new SqlCommand(StoredProcedures[5], new SqlConnection(ConnectionString));
            adapter.InsertCommand.CommandType = CommandType.StoredProcedure;

            SqlParameter insertParameter = null;
            insertParameter = adapter.InsertCommand.Parameters.Add("@IdGoods", SqlDbType.Int);
            insertParameter.Value = idGood;

            insertParameter = adapter.InsertCommand.Parameters.Add("@IdProperties", SqlDbType.Int);
            insertParameter.SourceColumn = "IdProperties";
            insertParameter.SourceVersion = DataRowVersion.Current;

            insertParameter = adapter.InsertCommand.Parameters.Add("@PropertieValue", SqlDbType.VarChar);
            insertParameter.SourceColumn = "PropertieValue";
            insertParameter.SourceVersion = DataRowVersion.Current;

            adapter.UpdateCommand = new SqlCommand(StoredProcedures[4], new SqlConnection(ConnectionString));
            adapter.UpdateCommand.CommandType = CommandType.StoredProcedure;

            SqlParameter updateParameter = null;
            updateParameter = adapter.UpdateCommand.Parameters.Add("@IdGoods", SqlDbType.Int);
            updateParameter.Value = idGood;

            updateParameter = adapter.UpdateCommand.Parameters.Add("@IdProperties", SqlDbType.Int);
            updateParameter.SourceColumn = "IdProperties";
            updateParameter.SourceVersion = DataRowVersion.Current;

            updateParameter = adapter.UpdateCommand.Parameters.Add("@PropertieValue", SqlDbType.VarChar);
            updateParameter.SourceColumn = "PropertieValue";
            updateParameter.SourceVersion = DataRowVersion.Current;
        }
        void createTablePropertie()
        {
            DataColumn dc = new DataColumn("IdProperties");
            tableProperties.Columns.Add(dc);

            dc = new DataColumn("CaptionProperties");
            tableProperties.Columns.Add(dc);

            dc = new DataColumn("PropertieValue");
            tableProperties.Columns.Add(dc);

            tableProperties.RowChanged += new DataRowChangeEventHandler(properties_RowChanged);
            tableProperties.TableNewRow += new DataTableNewRowEventHandler(properties_TableNewRow);

        }
        void properties_TableNewRow(object sender, DataTableNewRowEventArgs e)
        {

            adapter.Update(tableProperties);
        }

        void properties_RowChanged(object sender, DataRowChangeEventArgs e)
        {
            if (e.Action == DataRowAction.Change)
                adapter.Update(tableProperties);
        }

        private void ReferenceGoods_Load(object sender, EventArgs e)
        {
            CreateOptionsDataAdapter(idGood);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            DataTable dt = tableProperties;
        }
    }
}
